package com.dengcj.ecology.request;

import com.engine.common.util.ServiceUtil;
import com.engine.workflow.entity.publicApi.ReqOperateRequestEntity;
import com.engine.workflow.publicApi.WorkflowRequestOperatePA;
import com.engine.workflow.publicApi.impl.WorkflowRequestOperatePAImpl;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.workflow.webservices.*;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author dengchunjie
 * @Description: 工作流请求工具类
 * @date 2022/1/10 17:55
 */
public class RequestUtil {

    /**
     * 提交流程
     * @param operator 节点操作者
     * @param requestid 工作流请求ID
     * @param remark 签字意见
     * @return
     */
    public static boolean submit(int operator, String requestid, String remark){
        WorkflowServiceImpl wfService = new WorkflowServiceImpl();
        WorkflowRequestInfo requestInfo= new WorkflowRequestInfo();
        requestInfo.setRequestId(requestid);

        String result = wfService.submitWorkflowRequest(requestInfo, Util.getIntValue(requestid), operator, "submit",  remark);

        return "success".equals(result);
    }

    /**
     * 退回流程
     * @param operator 操作者
     * @param requestid 工作流请求ID
     * @param remark 签字意见
     * @return
     */
    public static boolean reject(int operator, String requestid, String remark){
        WorkflowServiceImpl wfService = new WorkflowServiceImpl();
        WorkflowRequestInfo requestInfo= new WorkflowRequestInfo();
        requestInfo.setRequestId(requestid);

        String result = wfService.submitWorkflowRequest(requestInfo, Util.getIntValue(requestid), operator, "reject",  remark);

        return "success".equals(result);
    }

    /**
     * 流程干预（以系统管理员身份）
     * @param requestId 必填	要干预的流程请求Id
     * @param submitNodeId 必填	目标节点ID
     * @param intervenorId 必填	干预节点接收人，多个人以","号隔开
     * @return
     */
    public static String intervenor(int requestId, int submitNodeId, String intervenorId){
        WorkflowRequestOperatePA operatePA = getRequestOperatePA();
        User user = new User(1);

        ReqOperateRequestEntity reqOperateRequestEntity = new ReqOperateRequestEntity();
        reqOperateRequestEntity.setRequestId(requestId);
        reqOperateRequestEntity.setSubmitNodeId(submitNodeId);
        reqOperateRequestEntity.setIntervenorid(intervenorId);

        Object apidatas = operatePA.doIntervenor(user, reqOperateRequestEntity);

        return apidatas.toString();
    }

    /**
     * 流程干预（以系统管理员身份）
     * @param requestId 必填	要干预的流程请求Id
     * @param submitNodeId 必填	目标节点ID
     * @param intervenorId 必填	干预节点接收人，多个人以","号隔开
     * @param signType 非必填	会签类型 0 ：非会签 1：会签 2：依次逐个处理
     * @param enableIntervenor 非必填	干预是否执行节点前附加操作
     * @param remark 非必填	操作意见
     * @return
     */
    public static String intervenor(int requestId, int submitNodeId, String intervenorId, int signType, boolean enableIntervenor, String remark){
        WorkflowRequestOperatePA operatePA = getRequestOperatePA();
        User user = new User(1);

        ReqOperateRequestEntity reqOperateRequestEntity = new ReqOperateRequestEntity();
        reqOperateRequestEntity.setRequestId(requestId);
        reqOperateRequestEntity.setSubmitNodeId(submitNodeId);
        reqOperateRequestEntity.setIntervenorid(intervenorId);
        reqOperateRequestEntity.setSignType(signType);
        reqOperateRequestEntity.setEnableIntervenor(enableIntervenor);
        reqOperateRequestEntity.setRemark(remark);

        Object apidatas = operatePA.doIntervenor(user, reqOperateRequestEntity);

        return apidatas.toString();
    }

    private static WorkflowRequestOperatePA getRequestOperatePA() {
        return ServiceUtil.getService(WorkflowRequestOperatePAImpl.class);
    }

    /**
     * 删除流程
     * @param operator 操作者
     * @param requestid 工作流请求ID
     * @return
     */
    public static boolean delete(int operator, int requestid){
        return new WorkflowServiceImpl().deleteRequest(requestid, operator);
    }

    /**
     * 创建流程
     * @param workflowId 流程ID
     * @param creator 创建人
     * @param requestName 流程名称
     * @param autoSubmit 是否提交到下一节点
     * @param mainFieldMap 主表字段
     * @param dtFieldList 明细表字段 可变参数
     * @return requestid
     * requestid = -1 创建流程失败
     * requestid = -2 用户没有流程创建权限
     * requestid = -3 创建流程基本信息失败
     * requestid = -4 保存表单主表信息失败
     * requestid = -5 更新紧急程度失败
     * requestid = -6 流程操作者失败
     * requestid = -7 流转至下一节点失败
     * requestid = -8 节点附加操作失败
     */
    public int create(String workflowId, String creator, String requestName, boolean autoSubmit, Map<String,Object> mainFieldMap, List<Map<String, Object>>... dtFieldList){
        int requestid = 0;
        int size = mainFieldMap.size();
        WorkflowRequestTableField[] wrti = new WorkflowRequestTableField[size];
        Set<String> keys = mainFieldMap.keySet();
        int i = 0;
        for(String key : keys){
            wrti[i] = new WorkflowRequestTableField();
            wrti[i].setFieldName(key);
            wrti[i].setFieldValue(mainFieldMap.get(key).toString());
            wrti[i].setView(true);
            wrti[i].setEdit(true);
            i++;
        }

        WorkflowRequestTableRecord[] wrtri = new WorkflowRequestTableRecord[1];// 主字段只有一行数据
        wrtri[0] = new WorkflowRequestTableRecord();
        wrtri[0].setWorkflowRequestTableFields(wrti);

        WorkflowMainTableInfo wmi = new WorkflowMainTableInfo();
        wmi.setRequestRecords(wrtri);

        WorkflowBaseInfo wbi = new WorkflowBaseInfo();
        wbi.setWorkflowId(workflowId);// workflowid

        WorkflowRequestInfo wri = new WorkflowRequestInfo();// 流程基本信息

        wri.setCreatorId(creator);// 创建人id

        wri.setRequestLevel("0");// 0 正常   1重要   2紧急
        wri.setRequestName(requestName);// 流程标题
        wri.setWorkflowMainTableInfo(wmi);// 添加主字段数据
        wri.setWorkflowBaseInfo(wbi);

        if(dtFieldList != null){
            int dtCount = dtFieldList.length;
            //明细字段
            WorkflowDetailTableInfo[] wdti = new WorkflowDetailTableInfo[dtCount];

            //开始逐个明细表处理
            for(int j=0; j<dtCount; j++){
                List<Map<String, Object>> dtData = dtFieldList[j];

                if(dtData == null){
                    continue;
                }
                wrtri = new WorkflowRequestTableRecord[dtData.size()];//数据行数

                int dtRowFieldCount = dtData.size();
                //逐行处理
                for(int k=0; k<dtRowFieldCount; k++){

                    Map<String, Object> rowData = dtData.get(k);
                    wrti = new WorkflowRequestTableField[rowData.size()]; //明细行
                    Set<String> dtKeys = rowData.keySet();
                    int m = 0;
                    for(String key : dtKeys){
                        wrti[m] = new WorkflowRequestTableField();
                        wrti[m].setFieldName(key);
                        wrti[m].setFieldValue(rowData.get(key).toString());
                        wrti[m].setView(true);
                        wrti[m].setEdit(true);
                        m++;
                    }
                    wrtri[k] = new WorkflowRequestTableRecord();
                    wrtri[k].setWorkflowRequestTableFields(wrti);
                }

                wdti[j] = new WorkflowDetailTableInfo();
                wdti[j].setWorkflowRequestTableRecords(wrtri);//加入明细表的数据
            }

            wri.setWorkflowDetailTableInfos(wdti);
        }

        if(autoSubmit){
            wri.setIsnextflow("1");
        } else {
            wri.setIsnextflow("0");
        }

        try {
            // 执行创建流程接口
            WorkflowServiceImpl impl = new WorkflowServiceImpl();
            requestid = Util.getIntValue(impl.doCreateWorkflowRequest(wri, Util.getIntValue(creator)));
        }catch (Exception e){
            e.printStackTrace();
        }

        return requestid;
    }
}
